<template>
  <div style="width:100%;height:100%;overflow:hidden">
    <weui-search-bar :list="search_bar_list" @on-search="onSearch" @on-input="onSearchBarInput">
    </weui-search-bar>
    <weui-panel title="" :list="panel_list" style="overflow-y:auto"
                :style="{maxHeight: 'calc(100% - ' + (isLoading ? 79 :54) + 'px)'}"
                @on-click="on_panel_click"
                @on-list="on_panel_list">
    </weui-panel>
    <div style="text-align:center">
      <weui-icon type="loading" v-show="isLoading">
      </weui-icon>
    </div>
  </div>
</template>

<script>
  import WeuiSearchBar from '../vue2componentSet/src/components/WeuiSearchBar'
  import WeuiPanel from '../vue2componentSet/src/components/WeuiPanel'
  import WeuiIcon from '../components/WeuiIcon'
  import global from '../lib/global'
  import browserDetect from '../lib/browserDetect'
  import axios from 'axios'

  export default {
    components: {
      WeuiSearchBar,
      WeuiPanel,
      WeuiIcon
    },
    data() {
      return {
        search_bar_list: [],
        possible_words_id: 0,
        panel_list: [],
        page: 1,
        word: '',
        isLoading: false,
        search_text: ''
      }
    },
    methods: {
      onSearch() {
        var word = this.search_text
        var type = word.substring(1, word.indexOf(']'))
        if (type == 'error')
          return
        word = word.substring(word.indexOf(']') + 1)
        this.$router.push('/?word=' + word)
        this.panel_list = []
        this.word = word
        this.page = 1
        this.search()
      },
      onSearchBarInput(word) {
        this.search_text = word
        if (word == '') {
          this.search_bar_list = []
          return
        }
        if (global.is_debug) {
          this.search_bar_list = ['java', 'node']
          return
        }
        this.possible_words_id++
        const possible_words_id = this.possible_words_id
        axios.post(global.server + 'getPossibleWords.do', {
          word: word
        }).then(result => {
          if (possible_words_id == this.possible_words_id) {
            const obj = result.data
            if (obj.result == -1) {
              this.search_bar_list = ['[error]' + obj.rmsg]
              return
            }
            var list = []
            obj.words.forEach(item => {
              list.push('[' + item.p + ']' + item.word)
            })
            this.search_bar_list = list
          }
        }, (response) => {
          console.log(response)
        })
      },
      on_panel_click(index) {
        if (!this.isLoading && index == this.panel_list.length - 1) {
          this.page = this.page + 1
          this.search()
          return
        }
        if (0 && browserDetect().Safari) {
          location.href = this.panel_list[index].desc
        } else {
          const node = document.getElementById('open-url')
          node.href = this.panel_list[index].desc
          node.click()
        }
        if (global.is_debug) {
          return
        }
        axios.post('/visit.do', {
          url: this.panel_list[index].desc
        }).then(result => {
          const obj = result.data
          if (obj.result == 1) {
          } else {
            this.$store.commit('toast', {
              type: 'warn',
              content: obj.msg
            })
          }
        }, (response) => {
          console.log(response)
        })
      },
      search(resolve) {
        if (this.word == '') {
          this.panel_list = []
          return
        }
        resolve = resolve || (() => {
        })
        if (global.is_debug) {
          if (this.panel_list.length > 0)
            this.panel_list.splice(this.panel_list.length - 1)
          for (var i = 0; i < 10; i++) {
            this.panel_list.push({
              title: '百度',
              desc: 'http://www.baidu.com',
              infos: [],
              list: [{
                label: 'edit',
                backgroundColor: 'blue',
                color: '#fff'
              }, {
                label: 'cache',
                backgroundColor: 'white',
                color: '#000'
              }, {
                label: 'delete',
                backgroundColor: 'red',
                color: '#fff'
              }],
              infos: ['aa(1)', '1']
            })
          }
          this.panel_list.push({
            title: '点击加载更多'
          })
          resolve()
          return
        }
        this.isLoading = true
        axios.post(global.server + 'search.do', {
          word: this.word,
          page: this.page
        }).then(result => {
          this.isLoading = false
          const obj = result.data
          if (obj.result == -1) {
            this.$store.commit('toast', {
              content: obj.msg,
              type: 'warn'
            })
          } else {
            this.search_bar_list = []
            if (this.panel_list.length > 0)
              this.panel_list.splice(this.panel_list.length - 1)
            obj.urls.forEach(url => {
              const item = {
                title: url.title,
                desc: url.url,
                img: url.img,
                infos: [],
                list: [{
                  label: 'edit',
                  backgroundColor: 'blue',
                  color: '#fff'
                }, {
                  label: 'cache',
                  backgroundColor: 'white',
                  color: '#000'
                }, {
                  label: 'delete',
                  backgroundColor: 'red',
                  color: '#fff'
                }]
              }
              url.words.forEach(word => {
                item.infos.push(word.word + '(' + word.p.toFixed(4) + ')')
              })
              item.infos.push(url.p.toFixed(4))
              this.panel_list.push(item)
            })
            this.panel_list.push({
              title: '点击加载更多'
            })
            resolve()
          }
        }, (response) => {
          this.isLoading = false
          console.log(response)
        })
      },
      on_panel_list(index, _index) {
        if (_index == 0) {
          this.$router.push('/edit?url=' + encodeURIComponent(this.panel_list[index].desc))
        } else if (_index == 1) {
          this.$router.push('/cache?url=' + encodeURIComponent(this.panel_list[index].desc))
        } else if (_index == 2) {
          if (global.is_debug) {
            this.panel_list.splice(index, 1)
            return
          }
          axios.post('/deleteUrlWord.do', {
            word: this.word,
            url: this.panel_list[index].desc
          }).then(result => {
            const obj = result.data
            if (obj.result == -1) {
              this.$store.commit('toast', {
                content: obj.msg,
                type: 'warn'
              })
            } else if (obj.result == 0) {
              this.$router.push('/login?redirectTo=' + encodeURIComponent(location.hash.substring(1)))
            } else {
              this.panel_list.splice(index, 1)
            }
          }, (response) => {
            console.log(response)
          })
        }
      }
    },
    mounted() {
      if (/^\/\d+\.page$/.test(location.pathname)) {
        this.$nextTick(() => {
          this.$router.redirect('/page')
        })
      }

      this.$store.commit('set_title', 'index')
      global.on_scroll_pullup_loading = resolve => {
        this.page = this.page + 1
        this.search(resolve)
      }

      var arr = location.hash.split('?')
      if (arr.length != 1) {
        arr[1].split('&').forEach(item => {
          var arr = item.split('=')
          if (arr[0] == 'word')
            this[arr[0]] = decodeURIComponent(arr[1])
        })
      }

      global.on_goback = (link) => {
        var word = ''
        var arr = link.split('?')
        if (arr.length != 1) {
          arr[1].split('&').forEach(item => {
            var arr = item.split('=')
            if (arr[0] == 'word')
              word = decodeURIComponent(arr[1])
          })
        }
        this.word = word
        this.search()
      }

      this.search()
    }
  }
</script>
